package com.mall.sun.handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.mall.sun.exception.TokenIsExpiredException;
import com.mall.sun.model.po.Permission;
import com.mall.sun.model.vo.ResultVO;
import com.mall.sun.repository.mapper.UserMapper;
import com.mall.sun.utils.JwtTokenUtils;
import com.mall.sun.utils.SpringUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * description:  <br>
 * date: 2021/8/5 13:20 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        } catch (TokenIsExpiredException e) {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = e.getMessage();
            response.getWriter().write(new ObjectMapper().writeValueAsString(new ResultVO("error", 403, reason)));
            response.getWriter().flush();
            return;
        }
        super.doFilterInternal(request, response, chain);
    }
    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        System.out.println(token);
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration) {
            throw new TokenIsExpiredException("token超时了");
        } else {
            String username = JwtTokenUtils.getUsername(token);
            // redis集成
            //RedisUtil redisUtil = new RedisUtil();
            //String rToken = null;
            //try {
            //    rToken = (String) redisUtil.get(username);
            //} catch (Exception e) {
            //    e.printStackTrace();
            //    return null;
            //}
            //if(!(rToken.equals(tokenHeader))){
            //    return null;
            //}
            String role = JwtTokenUtils.getUserRole(token);
            if (username != null) {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
                authorities.add(new SimpleGrantedAuthority(role));
                // 数据库中查出所具有的权限进行授权
                for (Permission permission : userMapper.findPermissionByUsername(username)) {
                    authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
                }
                return new UsernamePasswordAuthenticationToken(username, null,
                       authorities
                );
            }
        }
        return null;
    }

}
